package com.mnsq.common.helper;

import com.mnsq.common.bean.enums.TimeEnum;
import com.mnsq.common.service.RedisServer;
import com.mnsq.common.tools.tool.GenerateKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 周俭
 */
@Component
public class RedisHelper {
    @Autowired
    private RedisServer<String, String> redisServer;

    /**
     * save times
     * k:u,u,u,u  k-u:c
     *
     * @param unique
     * @param userId
     * @param sk     totalKey: a,b,c ==>> get: sk-a,sk-b,sk-c
     */
    public void timesRecord(String unique, Long userId, String sk) {
        if (unique == null || userId == null) {
            return;
        }
        String saveKey = sk + "-" + unique;
        String key = GenerateKey.readableKey(unique, userId);
        if (!redisServer.hasKey(key)) {
            redisServer.setValue(key, "1", TimeEnum.HOUR_TWENTY_FOUR.time);
            String s = redisServer.get(saveKey);
            Long counts = 1L;
            if (s != null) {
                counts += Long.valueOf(s);
            }
            redisServer.setValue(saveKey, counts + "", TimeEnum.HOUR_TWENTY_FOUR.time);
        } else {
            return;
        }
        String s = redisServer.get(sk);
        if (s == null) {
            s = unique;
        } else if (s.indexOf(unique) == -1) {
            s += "," + unique;
        } else {
            return;
        }
        redisServer.setValue(sk, s);
    }
}
